import os
import django
import random
from datetime import datetime, timedelta
from faker import Faker

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'boss.settings')
django.setup()

from django.db import transaction
from .models import Post, PostLike, PostStar, Comment
from user.models import User

fake = Faker('zh_CN')


def generate_test_data():
    """生成完整的测试数据"""

    # 获取所有用户
    users = list(User.objects.all())
    print(f"找到 {len(users)} 个用户")

    # 定义分类和标签
    categories = ['招聘', '面试', '薪酬', '培训', '企业文化', 'HR技巧', '行业分析', '员工关系']
    tags_list = ['招聘', '面试', '薪酬', '培训', '发展', '文化', 'HR', '技巧', '趋势', '分析', '员工', '管理']

    # 生成帖子数据
    posts = []
    for user in users:
        # 每个用户生成1-3个帖子
        num_posts = random.randint(1, 3)
        for _ in range(num_posts):
            post = Post(
                user=user,
                title=fake.sentence(),
                content=fake.text(max_nb_chars=1000),
                like_count=0,  # 初始为0，后面会根据点赞数据更新
                comment_count=0,  # 初始为0，后面会根据评论数据更新
                share_count=random.randint(0, 30),
                star_count=0,  # 初始为0，后面会根据收藏数据更新
                created_at=fake.date_time_between(start_date='-1y', end_date='now'),
                category=random.choice(categories),
                source=random.choice(['原创', '转载', '内部', '网络']),
                tags=','.join(random.sample(tags_list, 3))
            )
            posts.append(post)

    # 批量创建帖子
    Post.objects.bulk_create(posts)
    print(f"已生成 {len(posts)} 个帖子")

    # 获取所有帖子ID
    all_posts = list(Post.objects.all())
    post_ids = [post.id for post in all_posts]

    # 生成点赞数据
    likes = []
    for post in all_posts:
        # 每个帖子有0-50个点赞
        num_likes = random.randint(0, 50)
        post_like_users = random.sample(users, min(num_likes, len(users)))

        for user in post_like_users:
            like = PostLike(
                post=post,
                user=user,
                created_at=fake.date_time_between_dates(
                    datetime_start=post.created_at,
                    datetime_end=post.created_at + timedelta(days=30)
                )
            )
            likes.append(like)

    # 批量创建点赞
    PostLike.objects.bulk_create(likes)
    print(f"已生成 {len(likes)} 个点赞")

    # 更新帖子的点赞计数
    for post in all_posts:
        post.like_count = PostLike.objects.filter(post=post).count()
        post.save(update_fields=['like_count'])

    # 生成收藏数据
    stars = []
    for post in all_posts:
        # 每个帖子有0-30个收藏
        num_stars = random.randint(0, 30)
        post_star_users = random.sample(users, min(num_stars, len(users)))

        for user in post_star_users:
            star = PostStar(
                post=post,
                user=user,
                created_at=fake.date_time_between_dates(
                    datetime_start=post.created_at,
                    datetime_end=post.created_at + timedelta(days=30)
                )
            )
            stars.append(star)

    # 批量创建收藏
    PostStar.objects.bulk_create(stars)
    print(f"已生成 {len(stars)} 个收藏")

    # 更新帖子的收藏计数
    for post in all_posts:
        post.star_count = PostStar.objects.filter(post=post).count()
        post.save(update_fields=['star_count'])

    # 生成评论数据
    comments = []
    for post in all_posts:
        # 每个帖子有0-20条评论
        num_comments = random.randint(0, 20)
        post_comment_users = random.sample(users, min(num_comments, len(users)))

        for user in post_comment_users:
            comment = Comment(
                post=post,
                user=user,
                content=fake.text(max_nb_chars=200),
                created_at=fake.date_time_between_dates(
                    datetime_start=post.created_at,
                    datetime_end=post.created_at + timedelta(days=30)
                ),
                parent=None  # 只生成顶级评论
            )
            comments.append(comment)

    # 批量创建评论
    Comment.objects.bulk_create(comments)
    print(f"已生成 {len(comments)} 条评论")

    # 更新帖子的评论计数
    for post in all_posts:
        post.comment_count = Comment.objects.filter(post=post, parent=None).count()
        post.save(update_fields=['comment_count'])

    print("所有测试数据生成完成！")


if __name__ == '__main__':
    # 使用事务确保数据一致性
    with transaction.atomic():
        generate_test_data()
